<template>
 <ele-modal
    width="75%"
    :inner="false"
    :centered="true"
    :visible="visible"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="title"
    @update:visible="updateVisible"
    :append-to-body="true"
    :modal-append-to-body="true"
    v-if="visible"
  >
  <div >
    <el-row >
      <!-- <el-col :xl="6" :lg="6" :md="6" :sm="6" :xs="24" >
        <div class="Nav">
          <div class="input">
            <el-input
              search
              enter-button
              placeholder="请输入分类名称"
              v-model="uploadName.name"
              style="width: 90%"
              @on-search="changePage"
            />
          </div>
          <div class="trees-coadd">
            <div class="scollhide">
              <div class="trees">
                <el-tree
                  :data="treeData"
                  :render-content="renderContent"
                  :load-data="loadData"
                  class="treeBox"
                  ref="tree"
                ></el-tree>
              </div>
            </div>
          </div>
        </div>
      </el-col>-->
      <el-col :xl="20" :lg="20" :md="20" :sm="20" :xs="24" >
        <div class="conter">
          <div class="bnt acea-row row-middle">
            <el-col >
              <el-button
                type="primary"
                :disabled="checkPicList.length === 0"
                @click="checkPics"
                class="mr10"
                v-if="isShow !== 0"
                >使用选中数据</el-button
              >
              <el-upload
                :show-upload-list="false"
               
                class="mr10 mb10"
                :before-upload="beforeUpload"
                :data="uploadData"
                :show-file-list="false"
                :multiple="true"
                :accept=" fileType == 'video' ? 'video/mp4' : 'image/png,image/jpeg,image/png,image/gif'"
                :on-success="handleSuccess"
                action=""
                :http-request="handleHttpRequest"
                style="margin-top: 1px; display: inline-block"
              >
                <el-button type="primary">上传</el-button>
              </el-upload>
              <!--<Button type="success" @click.stop="add" class="mr10">添加分类</Button>-->
              <el-button
                type="error"
                class="mr10"
                :disabled="checkPicList.length === 0"
                @click.stop="editPicList('图片')"
                >删除</el-button>

           
              
          
            <!-- <el-select
                placeholder="图片移动至"
                style="width: 250px"
                class="treeSel"
              >
                <el-option
                  v-for="(item, index) of list"
                  :value="item.value"
                  :key="index"
                  style="display: none"
                >
                  {{ item.title }}
                </el-option>
                <el-tree
                  :data="treeData2"
                  :render="renderContentSel"
                  ref="reference"
                  :load-data="loadData"
                  class="treeBox"
                ></el-tree>
              </el-select>-->  
            </el-col>
          </div>
          <div class="pictrueList acea-row">
            <el-row :gutter="24" class="conter">
              <div v-show="isShowPic" class="imagesNo">
                <el-icon type="ios-images" size="60" color="#dbdbdb" />
                <span class="imagesNo_sp">图片库为空</span>
              </div>
              <div class="acea-row mb10">
                <div
                  class="pictrueList_pic mr10 mb10"
                  v-for="(item, index) in pictrueList"
                  :key="index"
                  @mouseenter="enterMouse(item)"
                  @mouseleave="enterMouse(item)"
                >
              
                    <el-badge :value="item.num" style="position: absolute;right: 12px;top: 16px;z-index: 9999;" v-if="item.num > 0" type="primary" :max="99"  >
                   
                    </el-badge>
               
                  <el-image
                    v-if="isImageFile(item.satt_dir)"
                    :class="item.isSelect ? 'on' : ''"
                    :src="item.satt_dir"
                    lazy
                    @click.stop="changImage(item, index, pictrueList)"
                  />

                  <video  
                    v-if="!isImageFile(item.satt_dir)"
                    :class="item.isSelect ? 'on' : ''"
                    :src="item.satt_dir"
                    lazy
                    @click.stop="changImage(item, index, pictrueList)"
                    width="100" height="100"
                  />

                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    "
                    @mouseenter="enterLeave(item)"
                    @mouseleave="enterLeave(item)"
                  >
                    <p style="width: 80%" v-if="!item.isEdit">
                      {{ item.editName }}
                    </p>
                    <el-input
                      size="small"
                      style="width: 80%"
                      type="text"
                      v-model="item.real_name"
                      v-else
                      @on-blur="bindTxt(item)"
                    />
                    <span
                      class="iconfont iconbianji1"
                      @click="item.isEdit = !item.isEdit"
                      v-if="item.isShowEdit"
                    ></span>
                  </div>
                  <div
                    class="nameStyle"
                    v-show="item.realName && item.real_name"
                  >
                    {{ item.real_name }}
                  </div>
                </div>
              </div>

              <p class="number" >
                    
                   

                    <el-pagination
                    @current-change="pageChange"
                    :page-size="18"
                    layout="total, prev, pager, next, jumper"
                    :total="total">
                  </el-pagination>

                  </p>
              <!--<Col class="mb20" v-bind="gridPic"-->
              <!--v-for="(item, index) in pictrueList" :key="index" >-->
              <!--<div class="pictrueList_pic">-->
              <!--<img :class="item.isSelect ? 'on': '' " v-lazy="item.satt_dir"-->
              <!--@click.stop="changImage(item, index, pictrueList)"/>-->
              <!--</div>-->
              <!--</Col>-->
            </el-row>
          </div>
          <div class="footer acea-row row-right">
           
          </div>
        </div>
      </el-col>
    </el-row>
     <!-- 编辑弹窗 -->
    <pic-edit
      :visible.sync="showEdit"
      :data="editData"
      :parent-id="parentId"
      :organizationlist="treeData"
      @done="getList"
    />
  </div>
  </ele-modal>
</template>

<script>
  import {
    getCategoryListApi,
    createApi,
    fileListApi,
    categoryEditApi,
    moveApi,
    fileUpdateApi,
  } from "@/api/uploadPictures";
  import {
    delCate,
    delFile
  } from '@/api/file';
  import PicEdit from './pic-edit';
  import request from '@/utils/request';
  export default {
    name: "uploadPictures",
    components: { PicEdit },
    props: {
    // 弹窗是否打开
      visible: Boolean,
      title: {
        type: String,
        default: "选择图片",
      },
      isChoice: {
        type: String,
        default: "",
      },
      gridBtn: {
        type: Object,
        default: null,
      },
      gridPic: {
        type: Object,
        default: null,
      },
      isShow: {
        type: Number,
        default: 1,
      },
      pageLimit: {
        type: Number,
        default: 0,
      },
      fileType: {
        type: String,
        default: "image",
      },
    },
    data() {
      return {
        // 懒加载
        value: undefined,
        initValue: undefined,
        showEdit:false,
        editData:null,
        parentId:'',
        spinShow: false,
        fileUrl:  "/file/upload",
        modalPic: false,
        treeData: [],
        treeData2: [],
        pictrueList: [],
        uploadData: {}, // 上传参数
        checkPicList: [],
        uploadName: {
          name: "",
        },
        FromData: null,
        treeId: 0,
        isJudge: false,
        buttonProps: {
          type: "default",
          size: "small",
        },
        fileData: {
          pid: 0,
          type:1,
          page: 1,
          limit: this.pageLimit || 18,
        },
        total: 0,
        pids: 0,
        list: [],
        modalTitleSs: "",
        isShowPic: false,
        header: {},
        ids: [], // 选中附件的id集合
      };
    },
    mounted() {
      this.getToken();
      this.getList();
      this.getFileList();
    },
    watch: {
      visible(visible) {
        if (visible) {
          
        } else {
            this.getList();
            this.getFileList();
            this.ids = [];
            //this.pictrueList = [];
            this.checkPicList = [];
            //this.getList();
        }
      }
    },
    methods: {
      isImageFile(url){
        // 获取文件扩展名
        const extension = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
        // 支持的图片扩展名列表
        const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
        // 判断当前文件扩展名是否为图片扩展名
        if (imageExtensions.includes(extension)) {
          return true;
        }
        return false;
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      },
      //打开弹框
      openPic(){
    
        //this.next
      },
      enterMouse(item) {
        item.realName = !item.realName;
      },
      enterLeave(item) {
        item.isShowEdit = !item.isShowEdit;
      },
      // 上传头部token
      getToken() {
      // this.header["Authori-zation"] = "Bearer " + getCookies("token");
      },
      // 树状图
      renderContent(h, { root, node, data }) {
        
        let operate = [];
        if(data.pid == 0){
    
          operate.push(<el-dropdown-item nativeOnClick={ () => { this.append(root, node, data);}}>添加分类</el-dropdown-item>);
        }
        if(data.id !== ""){
          operate.push(
          (<el-dropdown-item nativeOnClick={ () => { this.editPic(root, node, data);}}>编辑分类</el-dropdown-item>),
          (<el-dropdown-item nativeOnClick={ () => { this.remove(root, node, data);}}>删除分类</el-dropdown-item>));
        }

        return (<span class="ivu-span"  style='display:inline-block;width:88%; height:32px;lineHeight:32px;position:relative;'>
          <span onClick={(e)=>{  this.appendBtn(root, node, data, e);}}>{data.title}</span>
  
          <div style='display:inline-block;float:right;'>
          
            <el-dropdown style="marginRight:8px;fontSize:20px;display:inline;">
                <span class="el-dropdown-link">...</span>
                <el-dropdown-menu slot="dropdown">
                {operate}
                  
                </el-dropdown-menu>
            </el-dropdown>
          </div>
        </span>);
      
      },
      renderContentSel(h, { root, node, data }) {
        return h(
          "div",
          {
            style: {
              display: "inline-block",
              width: "90%",
            },
          },
          [
            h("span", [
              h(
                "span",
                {
                  style: {
                    cursor: "pointer",
                  },
                  class: ["ivu-tree-title"],
                  on: {
                    click: (e) => {
                      this.handleCheckChange(root, node, data, e);
                    },
                  },
                },
                data.title
              ),
            ]),
          ]
        );
      },
      // 下拉树
      handleCheckChange(root, node, data, e) {
        this.list = [];
        // this.pids = 0;
        let value = data.id;
        let title = data.title;
        this.list.push({
          value,
          title,
        });
        if (this.ids.length) {
          this.pids = value;
          this.getMove();
        } else {
          this.$message({
                message: '请先选择图片',
                type: 'error'
              });
          
        }
        let selected = this.$refs.reference.$el.querySelectorAll(
          ".ivu-tree-title-selected"
        );
        for (let i = 0; i < selected.length; i++) {
          selected[i].className = "ivu-tree-title";
        }
        e.path[0].className = "ivu-tree-title  ivu-tree-title-selected"; // 当前点击的元素
      },
      // 移动分类
      getMove() {
        let data = {
          pid: this.pids,
          images: this.ids.toString(),
        };
        moveApi(data)
          .then(async (res) => {
            this.$Message.success(res.msg);
            this.getFileList();
            this.pids = 0;
            this.checkPicList = [];
            this.ids = [];
          })
          .catch((res) => {
            
            this.$Message.error(res.msg);
          });
      },
      handleCommand(command) {
        
      },
      // 删除图片
      editPicList(tit) {
        this.tits = tit;
        
        delFile({ids:this.ids})
              .then((msg) => {
                this.$message.success(msg);
                this.getFileList();
                this.checkPicList = [];
              })
              .catch((e) => {
                this.$message.error(e.message);
              });
      },
      // 鼠标移入 移出
      onMouseOver(root, node, data) {
        // console.log('sss333',data);
      // event.preventDefault();
      // data.flag = !data.flag;
      //  if (data.flag2) {
      //    data.flag2 = false;
      // }
      },
      onClick(root, node, data, e) {
        e.preventDefault();

        data.flag2 = !data.flag2;
      },
      // 点击树
      appendBtn(root, node, data, e) {
        e.preventDefault();

        this.treeId = data.id;
        this.fileData.page = 1;
        this.getFileList();
        let selected = this.$refs.tree.$el.querySelectorAll(
          ".ivu-tree-title-selected"
        );
        for (let i = 0; i < selected.length; i++) {
          selected[i].className = "ivu-tree-title";
        }
        e.path[0].className = "ivu-tree-title  ivu-tree-title-selected"; // 当前点击的元素
      },
      // 点击添加
      append(root, node, data) {
        this.treeId = data.id;
        this.showEdit = true;
        this.parentId = data.id+"";
      // this.getFrom();
      },
      // 删除分类
      remove(root, node, data, tit) {


        

        delCate({id:data.id})
              .then((msg) => {
                this.$message.success(msg);
                this.getList();
                this.checkPicList = [];
              })
              .catch((e) => {
                this.$message.error(e.message);
              });

        
      },
    editPic(root, node, data) {
      
      this.showEdit = true;
      this.parentId = data.pid>0?data.pid:'';
      this.editData = data;
      //this.$modalForm(categoryEditApi(data.id)).then(() => this.getList());
    },
    // 搜索分类
    changePage() {
      this.getList("search");
    },
    // 分类列表树
    getList(type) {
      let data = {
        title: "全部图片",
        id: "",
        pid: 0,
      };
      getCategoryListApi({type:1,name:this.uploadName.name})
        .then(async (res) => {

         // 

          let result = this.$util.toTreeData({
              data: res,
              idField: 'id',
              parentIdField: 'pid'
            });
            this.treeData = result;
          this.treeData.unshift(data);

          if (type !== "search") {
            this.treeData2 = [...this.treeData];
          }
          this.addFlag(this.treeData);
        })
        .catch((res) => {
          this.$message.error(res.msg);
        });
    },
    loadData(item, callback) {
      getCategoryListApi({
        pid: item.id,
      })
        .then(async (res) => {
          const data = res.data.list;
          callback(data);
        })
        .catch((res) => {});
    },
    addFlag(treedata) {
      treedata.map((item) => {
        this.$set(item, "flag", false);
        this.$set(item, "flag2", false);
        item.children && this.addFlag(item.children);
      });
    },
    // 新建分类
    add() {
      this.treeId = 0;
      this.getFrom();
    },
    // 文件列表
    getFileList() {
      
      this.fileData.pid = this.treeId;
      
      fileListApi(this.fileData).then(async (res) => {
        res.list.forEach((el) => {
          el.isSelect = false;
          el.isEdit = false;
          el.isShowEdit = false;
          el.realName = false;
          el.num = 0;
          this.editName(el);
        });
        this.pictrueList = res.list;

        if (this.pictrueList.length) {
          this.isShowPic = false;
        } else {
          this.isShowPic = true;
        }
        this.total = res.count;
      }).catch((res) => {
        this.$message.error(res.msg);
      });
    },
    pageChange(index) {
      this.fileData.page = index;
      this.getFileList();
      this.checkPicList = [];
    },
    // 新建分类表单
    getFrom() {
      this.$modalForm(createApi({ id: this.treeId })).then((res) => {
        this.getList();
      });
    },
    // 上传之前
    beforeUpload(file) {
      // if (file.size > 2097152) {
      //   this.$Message.error(file.name + "大小超过2M!");
      // } else

      if(this.fileType == 'video'){
        const isMp4 = file.type === "video/mp4";
        if (!isMp4) {
          this.$message.error("视频只能是mp4格式!");
        }
      }else{
        if (!/image\/\w+/.test(file.type)) {
          this.$message.error("请上传以jpg、jpeg、png等结尾的图片文件"); //FileExt.toLowerCase()
          return false;
        }
      }

      
      this.uploadData = {
        pid: this.treeId,
      };
      let promise = new Promise((resolve) => {
        this.$nextTick(function () {
          resolve(true);
        });
      });
      return promise;
    },
    handleHttpRequest(option){ //上传文件
      try {
        option.status = 'uploading';
        const formData = new FormData();
        formData.append('file', option.file);
        formData.append('type', 1);
        formData.append('cid', this.treeId);
        request({
          url: '/common/uploadFile',
          method: 'post',
          data: formData,
          onUploadProgress: (e) => {  // 文件上传进度回调
              if (e.lengthComputable) {
                  option.progress = e.loaded / e.total * 100;
              }
          }
        }).then((res) => {
            this.$message.success("上传成功");
            this.fileData.page = 1;
            this.getFileList();
        }).catch((e) => {
          this.$message.error(e.message);
            option.status = 'exception';
        });

      } catch (error) {
          console.error(error);
          this.disabled = false;
          option.onError('上传失败');
      }
    },
    // 上传成功
    handleSuccess(res, file, fileList) {
     
     
    },
    // 关闭
    cancel() {
      this.$emit("changeCancel");
    },
    // 选中图片
    changImage(item, index, row) {
      let activeIndex = 0;
      if (!item.isSelect) {
        item.isSelect = true;
        this.checkPicList.push(item);
      } else {
        item.isSelect = false;
        this.checkPicList.map((el, index) => {
          if (el.id == item.id) {
            activeIndex = index;
          }
        });
        this.checkPicList.splice(activeIndex, 1);
      }

      this.ids = [];
      this.checkPicList.map((item, i) => {
        this.ids.push(item.id);
      });
      this.pictrueList.map((el, i) => {
        if (el.isSelect) {
          this.checkPicList.filter((el2, j) => {
            if (el.id == el2.id) {
              el.num = j + 1;
            }
          });
        } else {
          el.num = 0;
        }
      });
    },
    // 点击使用选中图片
    checkPics() {
      if (this.isChoice === "单选") {
        if (this.checkPicList.length > 1)
          return this.$message.warning("最多只能选一张图片");
        this.$emit("getPic", this.checkPicList[0]);
      } else {
        let maxLength = this.$route.query.maxLength;
        if (
          maxLength != undefined &&
          this.checkPicList.length > Number(maxLength)
        )
          return this.$message.warning("最多只能选" + maxLength + "张图片");
          debugger
        this.$emit("getPicD", this.checkPicList);
      }
    },
    editName(item) {
      let it = item.real_name.split(".");
      let it1 = it[1] == undefined ? [] : it[1];
      let len = it[0].length + it1.length;
      item.editName =
        len < 10
          ? item.real_name
          : item.real_name.substr(0, 2) + "..." + item.real_name.substr(-5, 5);
    },
    // 修改图片文字上传
    bindTxt(item) {
      if (item.real_name == "") {
        this.$message.error("请填写内容");
      }
      fileUpdateApi(item.att_id, {
        real_name: item.real_name,
      })
        .then((res) => {
          this.editName(item);
          item.isEdit = false;
          this.$message.success(res.msg);
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
  },
};
</script>

<style scoped lang="stylus">
.nameStyle {
  position: absolute;
  white-space: nowrap;
  z-index: 9;
  background: #eee;
  height: 20px;
  line-height: 20px;
  color: #555;
  border: 1px solid #ebebeb;
  padding: 0 5px;
  left: 56px;
  bottom: -18px;
}

.acea-row, .c_row-item {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
}
.acea-row {
    -webkit-box-lines: multiple;
    -moz-box-lines: multiple;
    -o-box-lines: multiple;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}

.iconbianji1 {
  font-size: 13px;
}

/deep/.ivu-badge-count {
  margin-top: 18px !important;
  margin-right: 19px !important;
}

/deep/ivu-tree-title-selected:hover {
  color: #2D8cF0 !important;
}

/deep/.ivu-tree-title {
  padding: 0;
  // width: 200px;
  width: 100%;
  
}

/deep/.ivu-span {
  padding: 0;
  display: flex !important;
  justify-content: space-between;
}

/deep/.ivu-tree ul li {
  margin: 0;
}

/deep/.ivu-tree-arrow {
  width: 17px;
  color: #626262;
}

/deep/.ivu-span:hover {
 color: #2D8cF0 !important;
}

/deep/.ivu-tree-arrow i {
  vertical-align: bottom;
}

.Nav /deep/.ivu-icon-ios-arrow-forward:before {
  content: '\F341' !important;
  font-size: 20px;
}

/deep/.ivu-btn-icon-only.ivu-btn-small {
  padding: unset !important;
}

.selectTreeClass {
  background: #d5e8fc;
}

.treeBox {
  width: 100%;
  height: 100%;

  >>> .ivu-tree-title-selected, .ivu-tree-title-selected:hover {
    color: #2D8cF0 !important;
 
  }

  >>> .ivu-btn-icon-only {
    width: 20px !important;
    height: 20px !important;
  }

  >>> .ivu-tree-title:hover {
    color: #2D8cF0 !important;
    
  }
}

.pictrueList_pic {
  position: relative;
  width: 100px;
  cursor: pointer;

  .el-image {
    width: 100%;
    height: 100px;
  }

  p {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    height: 20px;
    text-align: center;
  }

  .number {
    height: 33px;
  }

  .number {
    position: absolute;
    right: 20px;
    top: 15px;
  }
}

.trees-coadd {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  position: relative;

  .scollhide {
    overflow-x: hidden;
    overflow-y: scroll;
    padding: 10px 0 10px 0;
    box-sizing: border-box;

    .trees {
      width: 100%;
      height: 374px;
    }
  }

  .scollhide::-webkit-scrollbar {
    display: none;
  }
}

.treeSel >>>.ivu-select-dropdown-list {
  padding: 0 5px !important;
  box-sizing: border-box;
  width: 200px;
}

.imagesNo {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  margin: 65px 0;

  .imagesNo_sp {
    font-size: 13px;
    color: #dbdbdb;
    line-height: 3;
  }
}

.Modal {
  width: 100%;
  height: 100%;
  background: #fff !important;
}

.Nav {
  width: 100%;
 
}

.colLeft {
  padding-right: 0 !important;
  height: 100%;
}

.conter {
  width: 100%;
  height: 100%;
  margin-left: 0 !important;
}

.conter .bnt {
  width: 100%;
  padding: 0 13px 10px 8px;
  box-sizing: border-box;
}

.conter .pictrueList {
  padding-left: 6px;
  width: 100%;
  max-width: 1200px;
  overflow-x: hidden;
  overflow-y: auto;
  // height: 300px;
}

.conter .pictrueList .el-image {
  width: 100%;
  
}

.conter .pictrueList .el-image.on {
  border: 2px solid #5FB878;
}

.conter .footer {
  padding: 0 20px 10px 20px;
}

.demo-badge {
  width: 42px;
  height: 42px;
  background: transparent;
  border-radius: 6px;
  display: inline-block;
}

.bnt /deep/ .ivu-tree-children {
  padding: 5px 0;
}

.mb10 {
    margin-bottom: 15px!important;
}
.mr10 {
    margin-right: 10px;
}

.trees-coadd /deep/ .ivu-tree-children .ivu-tree-arrow {
  line-height: 25px;
}

.el-checkbox__inner::after {
  transition: none!important;
}

.el-dialog__wrapper{
  &.dialog-fade-enter-active{
    -ms-animation:none;
  }
  &.dialog-fade-leave-active{
    -ms-animation:none;
  }
}

</style>